<template>
  <div class="job-container">
     <!-- 职位列表 -->
    <div class="job-list">
      <!-- 职位卡片 -->
      <div
        v-for="job in jobList"
        :key="job.id"
        class="job-card"
        @mouseenter="handleMouseEnter(job.id)"
        @mouseleave="handleMouseLeave(job.id)"
      >
        <!-- 公司信息 -->
        <div class="company-info">
          <img
            :src="job.company.logo"
            :alt="job.company.name"
            class="company-logo"
          >
          <div class="company-detail">
            <h3 class="company-name">{{ job.company.name }}</h3>
            <p class="company-desc">{{ job.company.description }}</p>
          </div>
        </div>

        <!-- 职位核心信息 -->
        <div class="job-main">
          <h2 class="job-title">{{ job.title }}</h2>
          <div class="job-meta">
            <span class="salary">{{ job.money }}</span>
            <span class="city">{{ job.city.name }}</span>
            <span class="experience">{{ formatWorkingYears(job.working) }}</span>
            <span class="education">{{ job.education }}</span>
          </div>
          <div class="job-tags">
            <span class="tag">{{ job.label }}</span>
            <span class="tag type-tag">{{ formatJobType(job.type) }}</span>
          </div>
        </div>

        <!-- 底部信息 -->
        <div class="job-footer">
          <div class="hr-info">
            <img
              :src="job.hr.aveter"
              :alt="job.hr.name"
              class="hr-avatar"
            >
            <span class="hr-name">{{ job.hr.name }}</span>
            <span class="hr-position">{{ job.hr.position }}</span>
          </div>
          <div class="stats">
            <span>浏览 {{ job.browse_number }}</span>
            <span>收藏 {{ job.collect_number }}</span>
          </div>
        </div>

           <!-- AI筛选按钮 (鼠标悬停时显示) -->
        <button
          v-if="hoveredJobId === job.id"
          class="ai-filter-btn"
          @click="handleAIFilterClick(job.id)"
          :disabled="loadingJobIds.includes(job.id)"
        >
          <span v-if="loadingJobIds.includes(job.id)">
            <i class="fa fa-spinner fa-spin mr-1"></i>处理中...
          </span>
          <span v-else>
            <i class="fa fa-robot mr-1"></i>AI筛选简历
          </span>
        </button>

      </div>
    </div>

      <!-- 全局提示组件 -->
    <div v-if="showToast" class="toast-message" :class="toastType">
      {{ toastMessage }}
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

import { useRouter } from 'vue-router'
const router = useRouter()
// 状态管理
const hoveredJobId = ref(null);
const loadingJobIds = ref([]);
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref('');
const isHover = ref(false);
const jobList = ref([])
const form = reactive({
  job_id: '',
  resume_id: ''
})
const loading = ref(false)
const taskStatus = ref('')
const taskStatusMsg = ref('')
const taskStatusType = ref('info')
const taskResult = ref(null)
let ws = null
const user_id= localStorage.getItem('user.id')



// 获取职位列表  根据hr获取发布的所有职位id
const fetchJobs = async () => {
  const res = await axios.get('http://127.0.0.1:8000/job/hrjobList/', {params: {user_id:user_id || 2}})
  jobList.value = res.data.data
}



// 工具函数：格式化工作年限
const formatWorkingYears = (value) => {
  const yearMap = {
    1: '应届',
    2: '1-3年',
    3: '3-5年',
    4: '5-10年',
    5: '10年以上'
  };
  return yearMap[value] || '不限';
};

// 工具函数：格式化工作类型
const formatJobType = (value) => {
  const typeMap = {
    1: '全职',
    2: '兼职',
    3: '实习'
  };
  return typeMap[value] || '全职';
};


// 鼠标悬停事件处理
const handleMouseEnter = (jobId) => {
  hoveredJobId.value = jobId;
};

const handleMouseLeave = () => {
  hoveredJobId.value = null;
};

// AI筛选按钮点击事件
const handleAIFilterClick = async (jobId) => {
  if (loadingJobIds.value.includes(jobId)) return;
  loadingJobIds.value = [...loadingJobIds.value, jobId];
  try {
    // 1. 启动AI筛选任务（POST）
    const res = await axios.post('http://127.0.0.1:8000/job/aiScreening/', { job_id: jobId });
    if (res.data.code === 200) {
      showToastMessage('简历处理任务已启动', 'success');
      // 3. 跳转到详情页
      router.push({ path: '/aiHR', query: { job_id: jobId } });
      // 2. 启动WebSocket监听
      connectWebSocket(jobId);
    } else {
      showToastMessage(res.data.msg || '启动AI筛选失败', 'error');
    }
  } catch (error) {
    showToastMessage('启动AI筛选失败，请重试', 'error');
    console.error('AI筛选请求失败:', error);
  } finally {
    loadingJobIds.value = loadingJobIds.value.filter(id => id !== jobId);
  }
};

// 显示提示消息
const showToastMessage = (message, type = 'info') => {
  toastMessage.value = message;
  toastType.value = type;
  showToast.value = true;

  // 3秒后自动隐藏
  setTimeout(() => {
    showToast.value = false;
  }, 3000);
};



// WebSocket推送监听
const connectWebSocket = (jobId) => {
  if (ws) ws.close();
  ws = new WebSocket(`ws://127.0.0.1:8000/ws/screening/hr/${jobId}/`);
  ws.onopen = () => {
    console.log('WebSocket 连接已建立');
  };
  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.type === 'screening_result') {
      // 这里可以自动刷新简历列表或高亮新结果
      showToastMessage(`简历${data.deliverjob_id}评估完成！`, 'success');
      // 你可以在这里触发详情页的数据刷新
      // 比如用eventBus、pinia、vuex等全局通知刷新
    }
  };
  ws.onerror = () => {
    showToastMessage('WebSocket 连接异常', 'error');
  };
  ws.onclose = () => {
    console.log('WebSocket 关闭');
  };
};


onMounted(() => {
  fetchJobs();
});
</script>

<style scoped>
.job-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.page-header {
  text-align: center;
  margin: 30px 0 40px;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  color: #666;
  font-size: 16px;
}

.job-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 20px;
}

.job-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.job-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.company-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.company-logo {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: contain;
  margin-right: 12px;
  background: #f5f5f5;
}

.company-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.company-desc {
  color: #666;
  font-size: 14px;
}

.job-title {
  font-size: 20px;
  color: #1a1a1a;
  margin-bottom: 10px;
  font-weight: 600;
}

.job-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 12px;
  color: #666;
  font-size: 14px;
}

.salary {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.tag {
  padding: 4px 10px;
  background: #f5f5f5;
  border-radius: 4px;
  font-size: 13px;
  color: #666;
}

.type-tag {
  background: #e6f7ff;
  color: #1890ff;
}

.job-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  font-size: 13px;
  color: #999;
}

.hr-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.hr-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
}

.hr-name {
  color: #333;
  font-weight: 500;
}

.stats {
  display: flex;
  gap: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .job-list {
    grid-template-columns: 1fr;
  }

  .job-meta {
    gap: 8px;
  }

  .job-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>

